import pygame, tile

from pygame.locals import *
from tile import *

class SpriteManager():
    def __init__(self, path, dimensions, size):
        #path is to a spritesheet
        path = "images\%s" % (path)
        try:
            self.sheet = pygame.image.load(path).convert()
            self.dimensions = dimensions
            self.size = size
        except Exception, message:
            print "Unable to load spritesheet %s: %s" % (path, message)

    def imageFromID(self, ID, colorkey=True, colorkeyColor=(0, 0, 0)):
        #expects a 16x16 tilesheet of 8x8 tiles
        row = 0
        while ID >= self.dimensions[0]:
            row += 1
            ID -= self.dimensions[0]
        #now we know what row and column the image ID is. calculate the rect
        imageRect = pygame.Rect(ID * self.size, row * self.size, self.size, self.size)
        image = pygame.Surface(imageRect.size).convert()
        image.blit(self.sheet, (0, 0), imageRect)

        if colorkey is not None:
            if colorkey is -1:
                colorkey = image.get_at((0, 0))
            image.set_colorkey(colorkey, pygame.RLEACCEL)
        return image

    def imageFromPath(self, path, scale=True, useColorkey=None, colorkeyColor=(255, 255, 255)):
        path = "images\%s" % (path)
        try:
            image = pygame.image.load(path).convert()
            if scale:
                image = pygame.transform.scale(image, (16, 16))
            if useColorkey is not None:
                image.set_colorkey(colorkeyColor, RLEACCEL)
            print "SpriteManager loaded image %s" % (path)
            return image
        except Exception, message:
            print "SpriteManager failed to load image %s: %s" % (path, message)